package com.wnhz.work.jy.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wnhz.work.jy.BaseActivity;
import com.wnhz.work.jy.R;
import com.wnhz.work.jy.adapter.MyViewPagerAdapter;
import com.wnhz.work.jy.utils.AddImages;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * -------拍卖列表的item点击立即抢拍跳转到这里
 * --TODO 头部的可能的轮播图未写，轮播图高度
 */
public class GetSellCoin extends BaseActivity implements View.OnClickListener {
    private TextView title;
    private final int COUNT_DOWN = 411;
    private TextView tv_startTime, tv_endTime, tv_priceNow, tv_times, tv_timeLeft, tv_coinName, tv_submit;
    private EditText et_wantMoney;
    private View iv_coin;

    private String getId, inputMoney;

    private ViewPager viewPager;
    private LinearLayout indicatorLayout;
    private ArrayList<View> viewList = new ArrayList<>();// 添加了首尾的轮播图集合
    private List<String> autoPlayImages = new ArrayList<>();// 轮播图的图片资源集合
    private int currentPosition;
    private ImageView[] indicators;


    private long days;
    private long hours;
    private long minutes;
    private long se;
    private long diff;
    private int width;
    private TextView type_tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_sell_coin);
        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        width = wm.getDefaultDisplay().getWidth();
        initData();

        initView();
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewPager.getLayoutParams();
        params.height = (int) (width * 0.54);
        viewPager.setLayoutParams(params);
        chultime();
        handler.sendEmptyMessage(COUNT_DOWN);
    }

    private void initView() {
        type_tv = (TextView) findViewById(R.id.type);
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("拍卖");
        findViewById(R.id.btn_main_left).setOnClickListener(this);

        iv_coin = findViewById(R.id.iv_coin);

        tv_coinName = (TextView) findViewById(R.id.tv_coin_name);
        tv_timeLeft = (TextView) findViewById(R.id.tv_coin_timeLeft);//剩余时间， TODO 文字颜色未区分处理
        tv_startTime = (TextView) findViewById(R.id.tv_coin_startTime);
        tv_endTime = (TextView) findViewById(R.id.tv_coin_endTime);
        tv_priceNow = (TextView) findViewById(R.id.tv_coin_priceNow);
        tv_times = (TextView) findViewById(R.id.tv_coin_times);
        et_wantMoney = (EditText) findViewById(R.id.et_want_money);//输入竞拍价格
        tv_submit = (TextView) findViewById(R.id.tv_coin_submit);
        tv_submit.setOnClickListener(this);

        viewPager = (ViewPager) findViewById(R.id.homepager_viewpager);
        indicatorLayout = (LinearLayout) findViewById(R.id.homepager_indicator);

        initViewPager();
        setViewPager();


    }

    private void initData() {
        getId = getIntent().getStringExtra("id");//获取此硬币的id，用于获取详细数据
    }

    private void initViewPager() {
        /*for (int i = 0; i < imageResId.length; i++) {
            autoPlayImages.add(imageResId[i]);
        }*/
        int indicatorSize = autoPlayImages.size();

        indicators = new ImageView[indicatorSize];

        for (int i = 0; i < indicators.length; i++) {
            View view = LayoutInflater.from(GetSellCoin.this).inflate(R.layout.view_indicator, null);
            indicators[i] = (ImageView) view.findViewById(R.id.image_indicator);
            indicatorLayout.addView(view);
        }

        viewList = AddImages.addImageDatas(GetSellCoin.this, autoPlayImages);

        viewPager.setAdapter(new MyViewPagerAdapter(viewList));
    }

    private void setViewPager() {
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                currentPosition = arg0;
                if (currentPosition < 1) { // 首位之前，跳转到末尾（N）
                    setIndicator(autoPlayImages.size() - 1);
                } else if (currentPosition > autoPlayImages.size()) { // 末位之后，跳转到首位（1）
                    setIndicator(0);
                } else {

                    setIndicator(currentPosition - 1);
                }

            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                if (arg0 == 0) {
                    handler.removeMessages(11);
                    Message message = new Message();
                    message.what = 11;
                    handler.sendMessageDelayed(message, 3000);
                    viewPager.setCurrentItem(currentPosition, false);
                    if (viewList.size() > 1) { // 多于1，才会循环跳转
                        if (currentPosition < 1) { // 首位之前，跳转到末尾（N）
                            currentPosition = autoPlayImages.size(); // 注意这里是mList，而不是mViews
                            viewPager.setCurrentItem(currentPosition, false);
                        } else if (currentPosition > autoPlayImages.size()) { // 末位之后，跳转到首位（1）
                            viewPager.setCurrentItem(currentPosition, true); // false:不显示跳转过程的动画
                            viewPager.setCurrentItem(1, false); // false:不显示跳转过程的动画
                            currentPosition = 1;
                        }

                    }
                }

            }
        });

//        setIndicator(0);
        viewPager.setCurrentItem(1, false);
        handler.removeMessages(11);
        Message message = new Message();
        message.what = 11;
        handler.sendMessageDelayed(message, 3000);
    }

    public void chultime() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date1 = formatter.format(currentTime);
        // 获取服务器返回的时间戳 转换成"yyyy-MM-dd HH:mm:ss"
        //String date2 = groupResult.getEndTimeIos();
        String date2 = "2016-10-10 11:48:00";
        // 计算的时间差
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d1 = null;
        try {
            d1 = df.parse(date1);
            Date d2 = df.parse(date2);
            diff = d2.getTime() - d1.getTime();// 这样得到的差值是微秒级别
            diff = diff / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void gettiems() {
        days = diff / (60 * 60 * 24);
        hours = (diff - days * (60 * 60 * 24))
                / (60 * 60);
        minutes = (diff - days * (60 * 60 * 24) - hours
                * (60 * 60))
                / 60;
        se = (diff - days * (60 * 60 * 24) - hours
                * (60 * 60) - minutes * 60);
        hours = hours + days * 24;
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 11:
                    int position = currentPosition + 1;
                    viewPager.setCurrentItem(position, true);
                    break;
                case COUNT_DOWN:
                    if (diff > 0) {

                        String s1;
                        String s2;
                        gettiems();
                        /*if (se < 10) {
                            second.setText("0" + se);
                        } else {
                            second.setText("" + se);
                        }*/
                        if (minutes < 10) {
                            s2 = "0" + minutes;
                        } else {
                            s2 = "" + minutes;
                        }
                        if (hours < 10) {
                            s1 = "0" + hours;
                        } else {
                            s1 = "" + hours;
                        }

                        float f = (float) 1.5;
                        tv_timeLeft.setText(setSpannableString(s1, s2, 0xffff3c3c, f));
                        diff--;
                        handler.sendEmptyMessageDelayed(COUNT_DOWN, 1000);
                    } else {

                    }
                    break;
                default:
                    break;
            }
        }

    };


    /**
     * 设置指示器
     *
     * @param selectedPosition 默认指示器位置
     */
    private void setIndicator(int selectedPosition) {


        for (int i = 0; i < indicators.length; i++) {
            indicators[i].setBackgroundResource(R.drawable.icon_point);
        }
        if (indicators.length > selectedPosition)
            indicators[selectedPosition].setBackgroundResource(R.drawable.icon_point_pre);
    }

    public SpannableString setSpannableString(String s1, String s2, int color, float f) {
        String s = s1 + "小时" + s2 + "分";
        SpannableString member = new SpannableString(s);
        member.setSpan(new RelativeSizeSpan(f), 0, s1.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        member.setSpan(new RelativeSizeSpan(f), s.length() - s2.length() - 1, s.length() - 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        member.setSpan(new ForegroundColorSpan(color), 0, s1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        member.setSpan(new ForegroundColorSpan(color), s.length() - s2.length() - 1, s.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return member;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;

            case R.id.tv_coin_submit:

                inputMoney = et_wantMoney.getText().toString();

                if (inputMoney.length() > 0) {
                    doApply();
                } else {
                    MyToast("请输入竞价");
                }

                break;

            default:
                break;
        }
    }

    private void doApply() {
        /**
         *  TODO---网络请求的代码
         */
    }
}
